package com.zhglxt.web.controller.oa;

import com.zhglxt.common.annotation.Log;
import com.zhglxt.common.config.GlobalConfig;
import com.zhglxt.common.core.controller.BaseController;
import com.zhglxt.common.core.entity.AjaxResult;
import com.zhglxt.common.core.entity.sys.SysUser;
import com.zhglxt.common.core.page.TableDataInfo;
import com.zhglxt.common.enums.BusinessType;

import com.zhglxt.common.utils.ShiroUtils;
import com.zhglxt.common.utils.StringUtils;
import com.zhglxt.common.utils.WebUtil;
import com.zhglxt.framework.redisCache.IGlobalCache;
import com.zhglxt.framework.web.entity.server.Sys;
import com.zhglxt.oa.entity.BusinessTrip;
import com.zhglxt.oa.service.impl.BusinessTripServiceImpl;
import com.zhglxt.system.entity.SysPost;
import com.zhglxt.system.service.ISysPostService;
import com.zhglxt.system.service.ISysRoleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * @ClassName BusinessTripController
 * @Description TODO
 * @Author moyongjun
 * @Date 2022/5/19 20:38
 * @Version 1.0
 **/
@Controller
@RequestMapping("/oa/businessTrip")
public class BusinessTripController extends BaseController {
    private String prefix = "oa/businessTrip/";

    @Autowired
    private BusinessTripServiceImpl businessTripService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;
    /**
     * redis缓存操作
     */
    @Autowired
    private IGlobalCache iGlobalCache;

    /**
     * 跳转到请假列表页面
     *
     * @return
     */
    @RequiresPermissions("activiti:businessTrip:list")
    @RequestMapping("/list")
    public String businessTripList() {
        return prefix + "businessTripList";
    }

    /**
     * 查询请假列表数据
     *
     * @param request
     * @return
     */
    @RequiresPermissions("activiti:businessTrip:list")
    @RequestMapping("/getBusinessTripList")
    @ResponseBody
    public TableDataInfo getBusinessTripList(HttpServletRequest request) {
        startPage();
        Map<String, Object> paramMap = WebUtil.paramsToMap(request.getParameterMap());
        List<BusinessTrip> list = businessTripService.getBusinessTripList(paramMap);
        return getDataTable(list);
    }

    /**
     * 跳转到申请请假表单页面
     *
     * @param mmap
     * @return
     */
    @RequiresPermissions("activiti:businessTrip:add")
    @RequestMapping("/add")
    public String add(ModelMap mmap) {
        logger.info("跳转去请假申请页面：");
        logger.info("查询当前用户：");
        SysUser user = ShiroUtils.getSysUser();
//		mmap.put("roles", roleService.selectRoleAll());
        logger.info("当前用户是：{}", user);
        logger.info("查询当前用户的岗位信息：");
        List<SysPost> sysPosts = postService.selectPostsByUserId(user.getUserId());
        logger.info("查询当前用户的岗位信息：{}", sysPosts);

        for (SysPost sysPost : sysPosts) {
            if (sysPost.isFlag()) {
                // 返回的岗位信息
                logger.info("当前用户的岗位：{}", sysPost);
                mmap.put("post", sysPost);
                break;
            }
        }
        // 给前端页面返回数据
        mmap.put("user", user);

        return prefix + "businessTripAdd";
    }

    /**
     * 跳转到单独请假申请页面
     *
     * @param mmap
     * @return
     */
    @RequiresPermissions("activiti:businessTrip:add")
    @RequestMapping("/applay")
    public String businessTripApplay(ModelMap mmap) {
        logger.info("跳转去请假申请页面：");
        logger.info("查询当前用户：");
        SysUser user = ShiroUtils.getSysUser();
//		mmap.put("roles", roleService.selectRoleAll());
        logger.info("当前用户是：{}", user);
        logger.info("查询当前用户的岗位信息：");
        List<SysPost> sysPosts = postService.selectPostsByUserId(user.getUserId());
        logger.info("查询当前用户的岗位信息：{}", sysPosts);

        for (SysPost sysPost : sysPosts) {
            if (sysPost.isFlag()) {
                // 返回的岗位信息
                logger.info("当前用户的岗位：{}", sysPost);
                mmap.put("post", sysPost);
                break;
            }
        }
        // 给前端页面返回数据
        mmap.put("user", user);
        return prefix + "businessTripApplay";
    }

    /**
     * 保存请假申请表单数据
     *
     * @param request
     * @return
     */
    @Log(title = "请假申请管理", businessType = BusinessType.INSERT)
    @RequestMapping("/save")
    @ResponseBody
    public AjaxResult save(HttpServletRequest request) {
        if (GlobalConfig.isDemoEnabled()) {
            return error("演示模式不允许本操作");
        }
        Map<String, Object> paramMap = WebUtil.paramsToMap(request.getParameterMap());
        logger.info("保存请假申请表单参数：");
        paramMap.entrySet().forEach(entry -> {
            logger.info("参数是：key:{},value:{}", entry.getKey(), entry.getValue());
        });

        String flag = businessTripService.save(paramMap);
        if (flag.equals("1")) {
            return AjaxResult.success(StringUtils.format("保存成功"));
        } else if (flag.equals("2")) {
            return AjaxResult.success(StringUtils.format("操作成功"));
        } else {
            return AjaxResult.error(StringUtils.format("保存失败"));
        }

    }

    /**
     * 根据 ID 删除请假信息
     *
     * @param request
     * @return
     */
    @Log(title = "删除请假信息", businessType = BusinessType.UPDATE)
    @RequiresPermissions("activiti:businessTrip:remove")
    @RequestMapping("/remove")
    @ResponseBody
    public AjaxResult updateBusinessTripInFoByIds(HttpServletRequest request) {
        Map<String, Object> paramMap = WebUtil.paramsToMap(request.getParameterMap());
        if (GlobalConfig.isDemoEnabled()) {
            return error("演示模式不允许本操作");
        }
        return toAjax(businessTripService.updateBusinessTripInFoToArray(paramMap));
    }

    /**
     * 表单页面跳转
     *
     * @return
     */
    @RequestMapping("/form")
    public String form(BusinessTrip businessTrip, Model model) {
        logger.info("表单信息：");
        logger.info("参数businessTrip信息是：{}", businessTrip);

        // 请假审核表单页面
        String view = "businessTripAuditForm";
        // 准备一个businessTrip对象，给前端返回数据
        BusinessTrip lv = new BusinessTrip();
        // 请假id不为null,对已发起请假任务作处理
        if (StringUtils.isNotBlank(businessTrip.getId())) {
            logger.info("businessTrip持有的act是：{}", businessTrip.getAct());
            // 任务环节编号key,key对应流程定义文件找那个任务的key
            String taskDefKey = businessTrip.getAct().getTaskDefKey();
            logger.info("环节编号：{}", taskDefKey);

            /**
             * 查询请假信息
             */
            lv = businessTripService.getBusinessTripById(businessTrip);
            logger.info("查询得到的请假信息：{}" + lv);

            logger.info("任务是否结束：{}", businessTrip.getAct().isFinishTask());
            //请假详情，如果请假任务已结束，即销假,如果businessTrip对象持有的act任务对象的status是finish或者任务id是空,返回true
            if (businessTrip.getAct().isFinishTask()) {
                //请假审核信息查看页面
                logger.info("请假审核信息查看页面");
                view = "businessTripAuditView";
            }
            // 修改环节
            else if ("modifyApply".equals(taskDefKey)) {
                lv.setAct(businessTrip.getAct());
                logger.info("请假修改信息页面");
                /**
                 * 解决报错记录：Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:
                 * 出现这种问题的情况是由于JSON里面包含了实体没有的字段导致反序列化失败。
                 * 参考：https://www.cnblogs.com/EasonJim/p/7990909.html
                 */
                Object hget = iGlobalCache.hget("auditUserRecord", "auditUserForDept");
                logger.info("auditUser:{}", hget);
                SysUser auditUser = (SysUser) iGlobalCache.hget("auditUserRecord", "auditUserForDept");
                if (auditUser != null) {
                    lv.setAuditUserId(auditUser.getUserId());
                    lv.setAuditUserName(auditUser.getUserName());
                }

                view = "businessTripAuditForm";
            }// 部门经理审核环节
            else if ("deptAudit".equals(taskDefKey)) {
                lv.setAct(businessTrip.getAct());
                logger.info("部门经理审核页面");
                SysUser auditUser = (SysUser) iGlobalCache.hget("auditUserRecord", "auditUserForCEO");
                if (auditUser != null) {
                    lv.setAuditUserId(auditUser.getUserId());
                    lv.setAuditUserName(auditUser.getUserName());
                }

                view = "businessTripAudit";
            }
            // 总经理审核环节
            else if ("ceoAudit".equals(taskDefKey)) {
                lv.setAct(businessTrip.getAct());
                logger.info("HR审核页面");
                view = "businessTripAudit";
            }
            // 销假审核环节
            else if ("tripAudit".equals(taskDefKey)) {
                lv.setAct(businessTrip.getAct());
                logger.info("销假页面");
                logger.info("lv.getAct:{}" + lv.getAct());
                view = "businessTripAudit";
            }
        } else {
            // businessTrip id为空
            logger.info("businessTrip id 为空，返回请假填写表单页面和空数据！");
        }


        // 如果没有发起请假任务，跳转到请假申请表单页面,返回的lv对象的信息是没有设置值的
        logger.info("返回给页面的数据是：{}", lv);
        String toView = prefix + view;
        logger.info("要跳转到的页面是：{}", toView);
        // 给前端页面返回请假信息对象
        model.addAttribute("businessTrip", lv);
        return toView;
    }

    /**
     * 工单执行（完成任务）
     *
     * @param businessTrip
     * @return
     */
    @RequestMapping("/saveBusinessTripAudit")
    @ResponseBody
    public AjaxResult saveAudit(BusinessTrip businessTrip) {
        if (GlobalConfig.isDemoEnabled()) {
            return error("演示模式不允许本操作");
        }
        logger.info("工单提交后前端返回的数据是：{}", businessTrip);
        logger.info("工单提交后前端返回的flag是：{}", businessTrip.getAct().getFlag());
        logger.info("工单提交后前端返回的comment是：{}", businessTrip.getAct().getComment());
        logger.info("处理的任务环节是：{}", businessTrip.getAct().getTaskDefKey());
        if (!"tripAudit".equals(businessTrip.getAct().getTaskDefKey())) {
            logger.info("不是销假环节，处理的任务环节是：{}", businessTrip.getAct().getTaskDefKey());
            logger.info("当前处理的任务环节是：{}", businessTrip.getAct().getTaskDefKey());
            logger.info("检测工单提交数据必须需要的数据是否具备：{}");
            // 检查审核信息是否为空
            if (StringUtils.isBlank(businessTrip.getAct().getFlag()) || StringUtils.isBlank(businessTrip.getAct().getComment())) {
                logger.info("工单提交后前端返回的flag是：{}", businessTrip.getAct().getFlag());
                logger.info("工单提交后前端返回的comment是：{}", businessTrip.getAct().getComment());
                return AjaxResult.error(StringUtils.format("请检查任务流转标识是否正确或者审批意见是否为空。"));
            }
        }

        int auditSaveResult = businessTripService.auditSave(businessTrip);

        return AjaxResult.success(auditSaveResult);
    }
}
